const http = require('http');
const fs = require('fs');
const path = require('path');

const PORT = 8103;

const MIME_TYPES = {
  '.html': 'text/html',
  '.js': 'text/javascript',
  '.css': 'text/css',
  '.json': 'application/json',
  '.png': 'image/png',
  '.jpg': 'image/jpg',
  '.gif': 'image/gif',
  '.svg': 'image/svg+xml',
  '.wav': 'audio/wav',
  '.mp4': 'video/mp4',
  '.woff': 'application/font-woff',
  '.ttf': 'application/font-ttf',
  '.eot': 'application/vnd.ms-fontobject',
  '.otf': 'application/font-otf',
  '.wasm': 'application/wasm'
};

const server = http.createServer((req, res) => {
  console.log('Request received: ' + req.method + ' ' + req.url);
  
  let filePath = path.join(__dirname, req.url === '/' ? 'daka.html' : req.url);
  
  // 处理中文路径问题
  try {
    filePath = decodeURIComponent(filePath);
  } catch (err) {
    console.error('Error decoding URL:', err);
  }
  
  const extname = String(path.extname(filePath)).toLowerCase();
  const contentType = MIME_TYPES[extname] || 'application/octet-stream';

  fs.readFile(filePath, (error, content) => {
    if (error) {
      if (error.code === 'ENOENT') {
        // 文件未找到
        fs.readFile(path.join(__dirname, '404.html'), (err, notFoundContent) => {
          if (err) {
            // 如果没有404页面，返回简单错误信息
            res.writeHead(404, { 'Content-Type': 'text/html; charset=utf-8' });
            res.end('404 Not Found', 'utf-8');
          } else {
            res.writeHead(404, { 'Content-Type': 'text/html; charset=utf-8' });
            res.end(notFoundContent, 'utf-8');
          }
        });
      } else {
        // 其他服务器错误
        res.writeHead(500, { 'Content-Type': 'text/html; charset=utf-8' });
        res.end('Server Error: ' + error.code, 'utf-8');
      }
    } else {
      // 成功读取文件
      res.writeHead(200, { 'Content-Type': contentType + '; charset=utf-8' });
      res.end(content, 'utf-8');
    }
  });
});

server.listen(PORT, () => {
  console.log('Server running at http://localhost:' + PORT + '/');
  console.log('Press Ctrl+C to stop the server');
});